package com.ruoyi.business.thread;

import com.ruoyi.bizsys.domain.CustBindCardLog;
import com.ruoyi.bizsys.service.ICustBindCardLogService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.business.service.impl.BankCardSerivceImpl;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class BindBankCardThread extends Thread {

    private CustBindCardLog custBindCardLog;
    private RedisCache redisCache;
    private BankCardSerivceImpl bankCardSerivceImpl;
    private ICustBindCardLogService custBindCardLogService;

    public BindBankCardThread(CustBindCardLog custBindCardLog, RedisCache redisCache, BankCardSerivceImpl bankCardSerivceImpl, ICustBindCardLogService custBindCardLogService) {
        this.custBindCardLog = custBindCardLog;
        this.redisCache = redisCache;
        this.bankCardSerivceImpl = bankCardSerivceImpl;
        this.custBindCardLogService = custBindCardLogService;
    }

    public void run() {

        String redisName = "bind-bank-card-thread:" + custBindCardLog.getBindSerialNo();
        String threadName1 = "bind-bank-card-thread-" + custBindCardLog.getBindSerialNo();

        //设置线程名称
        Thread.currentThread().setName(redisName);

        //保存进redis
        redisCache.setCacheObject(redisName, threadName1);
        redisCache.expire(redisName, 185, TimeUnit.MINUTES);

        String cacheObject = redisCache.getCacheObject(redisName);

        //如果有缓存一直轮询
        while (cacheObject != null && !StringUtils.isBlank(cacheObject)) {

            bankCardSerivceImpl.verifyTransaction(custBindCardLog);

            //检查状态
            CustBindCardLog custBindCardLog1 = new CustBindCardLog();
            custBindCardLog1.setBindSerialNo(custBindCardLog.getBindSerialNo());
            List<CustBindCardLog> custBindCardLogList = custBindCardLogService.selectCustBindCardLogList(custBindCardLog1);
            if (StringUtils.equalsAny(custBindCardLogList.get(0).getTransStatus(), BizConstants.BIND_CARD_WAIT_CUST_SUBMIT, BizConstants.BIND_CARD_TRANS_PENDING)) {
                //休息十分钟
                try {
                    log.error(threadName1 + "线程准备睡眠");
                    Thread.sleep(1000 * 60 * 10);
                } catch (Exception e) {
                    log.error(threadName1 + "线程睡眠异常");
                }
                cacheObject = redisCache.getCacheObject(redisName);
            } else {
                //删除缓存
                redisCache.deleteObject(redisName);
                log.info(redisName + "Redis移除");
                cacheObject = null;
            }
        }
        log.info(threadName1 + "线程终止");

    }
}
